#include "LoadingCircleDialog.h"
#include <QPainter>
#include <QApplication>
#include <QFontMetrics>

LoadingCircleDialog::LoadingCircleDialog(QWidget *parent)
    : QDialog(parent),
    angle(0),
    displayText("加载中..."),
    backgroundColor(0, 0, 0, 80),
    textFont("Microsoft YaHei", 12, QFont::Normal), // 字体缩小为8号
    circleMargin(10),                             // 边距减少到20
    textVerticalOffset(55)                        // 文字下移量调整
{
    setWindowTitle("请稍候");
    setFixedSize(170, 170); // 尺寸缩小到150x150
    setWindowFlags(Qt::Dialog | Qt::FramelessWindowHint);
    setAttribute(Qt::WA_TranslucentBackground);

    timer = new QTimer(this);
    connect(timer, &QTimer::timeout, [this]() {
        angle = (angle + 12) % 360;
        update();
    });
}

void LoadingCircleDialog::showLoading(const QString &text)
{
    displayText = text;
    angle = 0;
    timer->start(40);
    show();
    QApplication::processEvents();
}

void LoadingCircleDialog::hideLoading()
{
    timer->stop();
    hide();
}

void LoadingCircleDialog::setText(const QString &text)
{
    displayText = text;
    update();
}

void LoadingCircleDialog::paintEvent(QPaintEvent *event)
{
    Q_UNUSED(event);
    QPainter painter(this);
    painter.setRenderHint(QPainter::Antialiasing);

    // 绘制透明背景
    painter.fillRect(rect(), backgroundColor);

    // 绘制旋转圆弧（尺寸适应小窗口）
    QPen pen(QColor(255, 255, 255, 220));
    pen.setWidth(5);  // 线条粗细微调
    painter.setPen(pen);
   painter.drawArc(rect().adjusted(40, 40, -40, -40), angle * 16, 270 * 16);
     // 绘制文本（自适应位置）
    painter.setFont(textFont);
    QFontMetrics fm(textFont);
    int textHeight = fm.height();

    // 计算文字区域（圆弧下方居中）
    QRect textRect = rect();
    textRect.setTop(rect().center().y() + textVerticalOffset);
    textRect.setHeight(textHeight);

    // 文字阴影
    painter.setPen(QColor(0, 0, 0, 60));
    painter.drawText(textRect.translated(3, 3), Qt::AlignCenter, displayText);

    // 文字主体
    painter.setPen(Qt::white);
    painter.drawText(textRect, Qt::AlignCenter, displayText);
}
